import { wxLogin, authUser } from '../../api/login';
import { setToken } from '../../utils/storage';
import { toDefaultPage } from '../../utils/navigate';

const app = getApp();
Component({
  lifetimes: {
    attached() {
      if (!app.globalData.token) {
        // 出现登录按钮
        this.setData({
          show: true,
        });
      }
      this.hideThis = this.hide.bind(this);
      // 监听全局token的变化
      app.observe(app.globalData, 'token', {
        watchKey: 'token',
        watch: this.hideThis,
      });
    },
    detached() {
      app.unObserve('token', this.hideThis);
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    show: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    hide(newVal) {
      if (newVal) {
        this.setData({ show: false });
      }
    },
    async authInfo() {
      //开始登陆
      try {
        wx.showLoading('登陆中...');
        const { code } = await wxLogin();
        const loginParams = { code };
        console.log(loginParams);
        let authInfo = await authUser(loginParams);
        console.log(authInfo);
        const { globalData } = getApp();
        wx.hideLoading();
        if (authInfo.token == '0') {
          //没有绑定手机号 去注册页面
          wx.showToast({ title: '请先绑定手机号码', icon: 'none' });
          //缓存openid
          globalData.openId = authInfo.wx_openid;
          wx.setStorageSync('openId', authInfo.wx_openid);
          wx.navigateTo({ url: '/pages/regist/regist' });
        } else if (authInfo.token) {
          //登陆成功 回到首页
          setToken(authInfo.token);
          getApp().globalData.homeNeedRefresh = true;
          this.setData({ show: false });
          toDefaultPage();
          this.triggerEvent('onAuthSuccess');
        } else {
          console.log('err');
          //报错
          wx.showToast({ title: '登陆失败', icon: 'none' });
        }
      } catch (error) {
        console.log(error);
        wx.showToast({ title: '登陆失败', icon: 'none' });
      }
    },
  },
});
